import {PageContainer} from "@ant-design/pro-layout";
import ProCard from "@ant-design/pro-card";
import ProTable, {ProTableProps} from "@ant-design/pro-table";
import {CustomerPCBAData, CustomerPCBAParams, CustomerPCBAAdd} from "@/pages/customerConsulting/pcba/type";
import columns from "@/pages/customerConsulting/pcba/list/config/columns";
import {Button, message, Space} from "antd";
import React, {useRef, useState} from "react";
import {ActionType} from "@ant-design/pro-table/lib/typing";
import {
  downloadCustomerPCBAExport,
  downloadCustomerPCBAExportTemplate,
  customerPCBAImport,
  customerPCBAUpdate,
  customerPCBAAdd,
  customerPCBAPageList,
  customerPCBARemove, downloadCustomerPCBAFile
} from "@/services/customer/pcba/api";
import {history} from "umi";
import {OptionActions} from "@/type/type";
import Upload from "@/components/Upload";
import AddCustomerPCBA from "@/pages/customerConsulting/pcba/list/components/AddCustomerPCBA";
import {ProFormInstance} from "@ant-design/pro-form";
import AuthWrapper from "@/components/AuthWrapper";


export default () => {

  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<(number | string)[]>([]);
  const [createTime, setCreateTime] = useState<(number | string)[]>([]);
  const customerPCBAAddRef: React.MutableRefObject<ProFormInstance<CustomerPCBAAdd> | undefined> = useRef<ProFormInstance<CustomerPCBAAdd> | undefined>();
  const optionAction: OptionActions<CustomerPCBAAdd, CustomerPCBAData> = {
    import: {
      maxCount: 1,
      showUploadList: false,
      beforeUpload: (file) => {
        const formData = new FormData();
        formData.append('file', file);
        customerPCBAImport(formData).then((res) => {
          actionRef?.current?.reload();
        });
      }
    },
    edit(data) {
      // @ts-ignore
      customerPCBAUpdate(data).then(res => {
        message.success("编辑成功成功").then(res => {
        })
        setSelectedRowKeys([]);
        actionRef.current?.reload();
      });
    },
    editModal: (data: CustomerPCBAData, authorized: boolean) => {
      return {
        trigger: <Button type="link" disabled={!authorized} onClick={() => {
          customerPCBAAddRef.current?.setFieldsValue(data)
        }}>编辑</Button>,
        onFinish: async (formData) => {
          await customerPCBAAddRef.current?.validateFields().then(res => {
            const customerPCBA: any = {
              ...formData,
              id: data.id
            }
            customerPCBAUpdate(customerPCBA).then(res => {
              message.success("操作成功")
              customerPCBAAddRef.current?.resetFields();
              actionRef.current?.reload();
            })
          })
          return true
        },
        formRef: customerPCBAAddRef,
        title: "新增客户询价",
      }
    },
    add() {
      history.push({
        pathname: "/add"
      })
    },
    addModal: (id, authorized) => {
      return {
        trigger: <Button disabled={!authorized} type="primary"
                         onClick={() => customerPCBAAddRef.current?.resetFields()}>新增</Button>,
        onFinish: async (formData) => {
          await customerPCBAAddRef.current?.validateFields().then(res => {
            customerPCBAAdd(formData as CustomerPCBAAdd).then(res => {
              message.success("新增成功")
              customerPCBAAddRef.current?.resetFields();
              actionRef.current?.reload();
            })
          })
          return true
        },
        formRef: customerPCBAAddRef,
        title: "新增客户询价",
      }
    },
    export() {
      downloadCustomerPCBAExport(selectedRowKeys).then(res => {
        message.success("导出成功").then(res => {
        })
        setSelectedRowKeys([]);

      })
    },
    remove(ids) {
      customerPCBARemove([...ids, ...selectedRowKeys]).then(res => {
        message.success("删除成功").then(res => {

        })
        setSelectedRowKeys([]);
        actionRef.current?.reload();
      });
    },
    exportTemplate() {
      downloadCustomerPCBAExportTemplate().then(res => {
        message.success("下载成功").then(res => {
        })
      })
    },
    download(id: number) {
      downloadCustomerPCBAFile(id).then(res => {
      })
    }
  }

  // @ts-ignore
  const tableProps
    :
    ProTableProps<CustomerPCBAData, CustomerPCBAParams> = {
    rowSelection: {
      // selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
      // selections: [],
    },
    tableAlertRender: ({selectedRowKeys, selectedRows, onCleanSelected}) => {
      setSelectedRowKeys(selectedRowKeys);
      return (
        <Space size={24}>
                      <span>
                          已选 {selectedRowKeys.length} 项
                          <a style={{marginInlineStart: 8}} onClick={onCleanSelected}>
                           取消选择
                         </a>
                      </span>
        </Space>
      );
    },
    tableAlertOptionRender: () => {
      return (
        <Space size={16}>
          <a onClick={() => optionAction.remove([])}>批量删除</a>
          <a onClick={() => optionAction.export()}>导出数据</a>
        </Space>
      );
    },
    tableStyle: {},
    size: "small",
    bordered: true,
    // @ts-ignore
    columns: columns(optionAction, setCreateTime),
    onReset:()=>{
      setCreateTime([])
    },
    request: async (params, sort, filter) => {
      params.beginTime = createTime [0];
      params.endTime = createTime [1];
      return await customerPCBAPageList(params).then(res => {
        return {
          data: res.data.records,
          success: true,
          total: res.data.total
        }
      })
    },
    headerTitle: (
      <Space>
        {/*<AuthWrapper authorize={":add"}>*/}
        {/*    {(authorized: boolean) => <AddCustomerPCBA {...optionAction.addModal(0, authorized)}/>}*/}
        {/*</AuthWrapper>*/}
        {/*<AuthWrapper authorize={":import"}>*/}
        {/*    {(authorized: boolean) =>  <Upload {...optionAction.import} disabled={!authorized}></Upload>}*/}
        {/*</AuthWrapper >*/}
        <Button type="primary" onClick={() => optionAction.export()}>导出</Button>
        {/*<Button type="primary" onClick={() => optionAction.exportTemplate()}>导出模版</Button>*/}
      </Space>
    ),
    actionRef,
    rowKey: "id"
  }
  return (
    <PageContainer>
      <ProCard>
        <ProTable<CustomerPCBAData, CustomerPCBAParams> {...tableProps}>
        </ProTable>
      </ProCard>
    </PageContainer>
  )
}
